﻿using System;
using System.Collections.Generic;
using System.Linq;
using Metro.Kashikoi.Common.ExceptionHandling;
using Metro.Kashikoi.Service.Common.Entity;
using Metro.Kashikoi.ServiceContract.Location;

namespace Metro.Kashikoi.Service.Location.Entity
{
    /// <summary>
    /// Repository
    /// </summary>
    static class Repository
    {
        /// <summary>
        /// Gets the organization by id.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="repository">The repository.</param>
        /// <param name="id">The id.</param>
        /// <returns>
        /// The organization.
        /// </returns>
        /// <exception cref="NotExistException">Throw when the entity does not exist.</exception>
        public static TEntity GetEntityById<TEntity>(this Repository<Region> repository,
            int id) where TEntity : Region
        {
            var entity = repository.GetEntity<TEntity>(o => o.Id == id && o.Deleted == false);
            if (entity == null)
            {
                throw new NotExistException
                {
                    Entity = typeof(TEntity).Name,
                    Value = id
                };
            }
            return entity;
        }

        /// <summary>
        /// Gets the entity .
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="repository">The repository.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// The entity.
        /// </returns>
        public static TEntity GetEntity<TEntity>(this Repository<Region> repository,
            Func<TEntity, bool> predicate) where TEntity : Region
        {
            if (repository.Count<TEntity>(predicate) == 1)
            {
                var entity = repository.Single<TEntity>(predicate);
                return entity;
            }
            else
            {
                return null;
            }
        }

        #region Private Methods

        #endregion
    }
}
